package com.dycong.common.reflect.Reflect;



import com.dycong.common.reflect.Reflect.fruits.Apple;
import com.dycong.common.reflect.Reflect.fruits.fruit;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by dycong on 2016/12/10.
 */
public class LogHandler implements InvocationHandler {
    private Logger logger=Logger.getLogger(this.getClass().getName());

    private Object delegate;


    /*作用起始就是用接口回调实例来创建一个代理类*/
    public Object bind(Object delegate){
        this.delegate=delegate;
        return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                /*被代理的接口*/
                delegate.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)throws Throwable{
        Object result = null;
        try {
            logger.log(Level.INFO,
                    "method starts..." + method.getName());
            result = method.invoke(delegate, args);
            logger.log(Level.INFO,
                    "method ends..." + method.getName());
        } catch (Exception e){
            logger.log(Level.INFO, e.toString());
        }
        return result;
    }
    public static void main(String[] args) {
        LogHandler handler  = new LogHandler();
        fruit speaker = (fruit)new Apple("appleSpeaker","black");

        // 代理speaker的物件
        fruit speakerProxy =
                (fruit) handler.bind(speaker);

        speakerProxy.eat();
        speakerProxy.love("A3");
    }
}
